package com.ycsj.common.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.lzy.okgo.OkGo;
import com.ycsj.common.R;
import com.ycsj.common.utils.ScreenUtils;
import com.ycsj.common.utils.StateBarUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Calendar;

import butterknife.ButterKnife;


/**
 * 封装的Activity基类
 * Created by Administrator on 2017/12/21 0021.
 */

public abstract class BaseActivity extends AppCompatActivity {

    private static boolean isMiUi = false;

    /**
     * 防止点击过快的时间间隔
     */
    public static final long NO_DOUBLE_CLICK_TIME = 500;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(getContentLayout());

        //使用注解绑定
        ButterKnife.bind(this);

        //设置状态栏颜色(不含沉浸效果)
        StateBarUtil.customStateBar(this, getResources().getColor(R.color.state_color));

        //改变状态栏的字体为深色字体
//        StateBarUtil.setStatusBarLightMode(this, true);

        //每次初始化的时候就将当前activity加入到全局的ActivityStack中
        AppManager.getInstance().add(this);

        //注册EventBus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        //初始化Title,采用空实现
        setTitle();

        //初始化数据的方法
        init();

    }

    /**
     * 初始化头部的数据的方法,采用空实现的方法
     */
    protected void setTitle() {
    }

    /**
     * 返回内容布局ID的方法
     *
     * @return
     */
    protected abstract int getContentLayout();

    /**
     * 初始化的方法
     */
    protected abstract void init();


    /**
     * EventBus的接受事件的方法
     *
     * @param busInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busEvent(BusInfo busInfo) {
    }


    @Override
    protected void onDestroy() {
        //注销EventBus
        EventBus.getDefault().unregister(this);
        //取消全局默认的OkHttpClient中的所有请求
        OkGo.getInstance().cancelAll();
        super.onDestroy();
    }

    /**
     * 全局事件分发 实现 触摸非输入框控件 隐藏键盘
     *
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * 是否隐藏软键盘
     *
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();

//            if (event.getX() > left && event.getX() < right
//                    && event.getY() > top && event.getY() < bottom) {
//                // 点击的是输入框区域，保留点击EditText的事件
//                return false;
//            } else {
//                return true;
//            }


            if (event.getX() > 0 && event.getX() < ScreenUtils.getScreenWidth(this)
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 防止按钮重复点击的方法
     */
    protected boolean isDoubleClick(View v) {
        Object tag = v.getTag(v.getId());
        long beforeTimemiles = tag != null ? (long) tag : 0;
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        v.setTag(v.getId(), timeInMillis);
        return timeInMillis - beforeTimemiles < NO_DOUBLE_CLICK_TIME;
    }

    /**
     * 显示加载布局的方法,隐藏内容布局
     */
    protected void showLoading(View rlLoading, View contentView) {
        if (rlLoading != null && rlLoading.getVisibility() != View.VISIBLE) {
            rlLoading.setVisibility(View.VISIBLE);
        }

        if (contentView != null && contentView.getVisibility() != View.GONE) {
            contentView.setVisibility(View.GONE);
        }

    }


    /**
     * 沉浸状态栏
     */
    protected void initStateBar() {
        StateBarUtil.customImmerseBar(this);
    }

    /**
     * 隐藏加载布局,显示内容布局
     */
    protected void showContent(View rlLoading, View contentView) {
        if (rlLoading != null && rlLoading.getVisibility() != View.GONE) {
            rlLoading.setVisibility(View.GONE);
        }

        if (contentView != null && contentView.getVisibility() != View.VISIBLE) {
            contentView.setVisibility(View.VISIBLE);
        }
    }


    /*--------------------------------------针对小米手机和魅族手机改变状态文字颜色为黑色的方法----------------------------------------------------------*/

    /**
     * 设置小米黑色状态栏字体
     */
    @SuppressLint("PrivateApi")
    private void setMIUIStatusBarDarkMode() {
        if (isMiUi) {
            Class<? extends Window> clazz = getWindow().getClass();
            try {
                int darkModeFlag;
                Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                extraFlagField.invoke(getWindow(), darkModeFlag, darkModeFlag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * 静态域，获取系统版本是否基于MIUI
     */

    static {
        try {
            @SuppressLint("PrivateApi") Class<?> sysClass = Class.forName("android.os.SystemProperties");
            Method getStringMethod = sysClass.getDeclaredMethod("get", String.class);
            String version = (String) getStringMethod.invoke(sysClass, "ro.miui.ui.version.name");
            isMiUi = version.compareTo("V6") >= 0 && Build.VERSION.SDK_INT < 24;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 设置魅族手机状态栏图标颜色风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean setMeiZuDarkMode(Window window, boolean dark) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 24) {
            return false;
        }
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @SuppressLint("InlinedApi")
    private int getStatusBarLightMode() {
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (isMiUi) {
                result = 1;
            } else if (setMeiZuDarkMode(getWindow(), true)) {
                result = 2;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                result = 3;
            }
        }
        return result;
    }

    @SuppressLint("InlinedApi")
    protected void setStatusBarDarkMode() {
        int type = getStatusBarLightMode();
        if (type == 1) {
            setMIUIStatusBarDarkMode();
        } else if (type == 2) {
            setMeiZuDarkMode(getWindow(), true);
        } else if (type == 3) {
            //注意这里设置的满屏的操作样式
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

}
